package com.huarui.receive.action;

import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;

import com.huarui.part.model.PartPropertySearch;
import com.huarui.receive.model.Receive;
import com.huarui.receive.model.ReceiveModel;
import com.huarui.receive.service.ReceiveService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.ConstantUtil;
import com.huarui.util.JsonUtil;
import com.opensymphony.xwork2.Action;

public class ReceivesAction extends BaseAction {

	private static final long serialVersionUID = 3942259077332932935L;
	private static final Logger log = Logger.getLogger(ReceivesAction.class);
	private ReceiveService receiveService;
	private String queryParam;  //前台查询参数
    private JSONObject jsonResult = new JSONObject();
	// 分页
	private Integer start;
	private Integer limit;
	private String sort;
	private String dir;

	private SessionMessage sessionMessage;
  
	
	@SuppressWarnings("unchecked")
	private ListModel receiveModelList = new ListModel();
	private String searchJson;

	
	 /**
	  * 获得页面初始化按钮
	  * @return
	  */
	 public String getInitialButtons(){
		 sessionMessage = UserHolder.getCurrentSessionMessage();
		 jsonResult = receiveService.generateButtonsByStatus(Receive.STATUS_TO_CREATE, sessionMessage.getUserId(), sessionMessage.getUserId());
		 return SUCCESS;
	 }
	/**
	 * 根据订单号id查询订单主表及明细表	
	 * @param orderId
	 * @return  {'success':true,'main':{xxxx},'details':[{xxx},{xxxxx}...],'buttons':{'isOwner':true/false,'buttons':[{xxxx},{xxxx}...]},'msg':{'confirm'/'alert':xxxxx}}
	 *   "{'success':false,'msg':'发生异常'}"
	 */
	public String getOrderDetailExt(){		
		try {
			jsonResult = receiveService.generateReceiveAndItemsByOrderId(Integer.valueOf(queryParam));
			jsonResult.put(ConstantUtil.SUCCESS, true);			
		} catch (Exception e) {		
			log.error("查询采购订单失败.....",e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG, ConstantUtil.MSG_GET_DETAIL_FAILURE);
			
		}
		return Action.SUCCESS;

	}
    /**
     * 显示采购订单明细
     */
	public String acceptOrderToReceive(){		
		try {
			jsonResult = receiveService.acceptOrderToReceiveByOrderId(Integer.valueOf(queryParam));					
		} catch (Exception e) {			
		    log.error(ConstantUtil.QUOTE_OREDERS_FAILURE,e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,ConstantUtil.QUOTE_OREDERS_FAILURE);
		}		
		return SUCCESS;
	}
	/**
	 * 保存草稿
	 * @return
	 */
	public String backupDraft(){
		try {
			jsonResult = receiveService.backupDraft(queryParam);
		} catch (Exception e) {
			log.error("保存入库单草稿失败....",e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"保存入库单草稿失败....");	
		}
		return SUCCESS;
	}
	/**
	 * 保存待入库单
	 * @return
	 */
	public String submit(){
		try {
			jsonResult = receiveService.backupToInventory(queryParam);
		} catch (Exception e) {
			log.error("待入库单保存失败....",e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"待入库单保存失败....");	
		}
		return SUCCESS;
	}
	/**
	 * 入库
	 * @return
	 */
	public String deposit(){
		try {
			jsonResult = receiveService.backupInventory(queryParam);
		} catch (Exception e) {
			log.error("入库单入库失败....",e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"入库单入库失败....");	
		}
		return SUCCESS;
	}
	/**
	 * 接手单据
	 * @return
	 */
	public String acceptReceive(){
		sessionMessage = UserHolder.getCurrentSessionMessage();
		try {
			jsonResult = receiveService.updateReceiveCurrentorIdById(Integer.valueOf(queryParam),sessionMessage.getUserId());
		} catch (Exception e) {			
			log.error("接手单据 失败....",e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"接手单据 失败....");			
		}	
		return SUCCESS;
	}
	/**
	 * 释放单据
	 * {"isOwner":xxxxx,"buttons":[{xxxx},{xxxx}...],'success':true}
	 * or {'success':false}
	 */
	public String releaseReceive(){
		try {
			jsonResult = receiveService.updateReceiveCurrentorIdById(Integer.valueOf(queryParam),null);
		} catch (Exception e) {			
			log.error(e.getMessage(),e);
			jsonResult.put("释放单据 失败....", false);
			jsonResult.put(ConstantUtil.MSG,"释放单据 失败....");			
		}	
		return SUCCESS;
	}
	/**
	 * 待入库状态下根据入库单id,将单据退回草稿状态
	 */
	
    public String backToDraft(){
		try {
			jsonResult = receiveService.updateReceiveStatusById(Integer.valueOf(queryParam));
		} catch (Exception e) {			
			log.error(e.getMessage(),e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,ConstantUtil.MSG_BACKTO_DRAFT_FAILURE);				
		}
		return SUCCESS;
	}
	/**
	 * 草稿状态下，根据入库单id删除单据
	 */
	public String deleteDraft(){
		try {
			jsonResult = receiveService.deleteReceiveById(Integer.valueOf(queryParam));	
		} catch (Exception e) {
			log.error(e.getMessage());
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,ConstantUtil.MSG_DELETE_DRAFT_FAILURE);
		}		
		return SUCCESS;
	}
	
	/**
	 * 返回浏览入库单
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String fillReceiveBrowser(){
		sessionMessage = UserHolder.getCurrentSessionMessage();
		Map queryMap = new HashMap();
		if (queryParam != null) {
			JSONObject queryObject = JSONObject.fromObject(queryParam);
			queryMap = (Map) JSONObject.toBean(queryObject, java.util.Map.class);
		}			
		receiveModelList = listModelParamUtil();		
		ListModel<ReceiveModel> rList = receiveService.getReceiveListModelByConditons(queryMap, receiveModelList,sessionMessage);
		jsonResult.put(ConstantUtil.TOTALPROPERTY, rList.getTotal());
		jsonResult.put(ConstantUtil.ROOT, rList.getResult());		
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private ListModel listModelParamUtil() {
		receiveModelList.setPage(start ==null && limit == null ? 1: start / limit + 1);
		//receiveModelList.setStart(start == null ? 0 : start);
		receiveModelList.setPageSize(limit == null ? ConstantUtil.PAGESIZE : limit);
		receiveModelList.setOrderBy(sort);
		if (dir != null){
			receiveModelList.setDesc(dir.equals(ConstantUtil.DESC) ? true : false);
		}else{
			receiveModelList.setDesc(true);
		}		
		return receiveModelList;
	}

	/**
	 * 浏览入库单明细
	 */
	@SuppressWarnings("unchecked")
	public String fillReceiveItemBrowser(){
		sessionMessage = UserHolder.getCurrentSessionMessage();
		Map queryMap = new HashMap();
		try {
			if(queryParam != null){
				JSONObject queryObject = JSONObject.fromObject(queryParam);
				queryMap = (Map) JSONObject.toBean(queryObject, Map.class);	
			}	
			if(searchJson!=null){
				PartPropertySearch partPropertySearch=JsonUtil.getBean(searchJson, PartPropertySearch.class);
				queryMap.put("searchJson", partPropertySearch);
			}
			receiveModelList=listModelParamUtil();		
			ListModel<Map> mlist = receiveService.getReceiveItemByConditons(queryMap, receiveModelList,sessionMessage);	
			jsonResult.put(ConstantUtil.SUCCESS, true);
			jsonResult.put(ConstantUtil.TOTALPROPERTY, String.valueOf(mlist.getTotal()));
			jsonResult.put(ConstantUtil.ROOT, JSONArray.fromObject(mlist.getResult()).toString());
		} catch (Exception e) {			
			log.error("加载入库明细失败.....",e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG,"加载入库明细失败.....");
		}
		return SUCCESS;
	}
	
	/**
	 * 由浏览入库单转至入库单编辑(desktop)
	 */
	public String getReceiveAndItemById(){
		sessionMessage = UserHolder.getCurrentSessionMessage();
		try {
			jsonResult = receiveService.getReceiveAndItemsById(Integer.valueOf(queryParam),sessionMessage);
			jsonResult.put(ConstantUtil.SUCCESS,true);
			jsonResult.put(ConstantUtil.MSG, "");
		} catch (Exception e) {			
			log.error(e.getMessage(), e);
			jsonResult.put(ConstantUtil.SUCCESS, false);
			jsonResult.put(ConstantUtil.MSG, ConstantUtil.MSG_GET_DETAIL_FAILURE);
		}	
		return SUCCESS;
	}
	
	public String getQueryParam() {
		return queryParam;
	}

	public void setQueryParam(String queryParam) {
		this.queryParam = queryParam;
	}

	public Integer getStart() {
		return start;
	}

	public void setStart(Integer start) {
		this.start = start;
	}

	public Integer getLimit() {
		return limit;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	@SuppressWarnings("unchecked")
	public ListModel getReceiveModelList() {
		return receiveModelList;
	}

	@SuppressWarnings("unchecked")
	public void setReceiveModelList(ListModel receiveModelList) {
		this.receiveModelList = receiveModelList;
	}

	public void setReceiveService(ReceiveService receiveService) {
		this.receiveService = receiveService;
	}

	public JSONObject getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(JSONObject jsonResult) {
		this.jsonResult = jsonResult;
	}
	public void setSearchJson(String searchJson) {
		this.searchJson = searchJson;
	}
	
}
